<template>
    <div class="document content">

        <layout-detail :bread="bread">
            <template slot="left">
                <layout-card class="file">
                    <page-list :data="tableData" :total="total" :title="docname" @download="downloadAll">
                        <template slot="end">
                            <btn-load :remain="pageRemain" @click="loadMoreHandler"></btn-load>
                        </template>
                    </page-list>

                    <paper-foot layouts="like,collect,share,downloads" :data="detail" @download="downloadAll" search-url="/search/document" major-special
                        type="document" :rowguid="detail.guid">
                        <div class="copyright" slot="bottom-top">
                            版权说明：本文档由用户提供并上传，收益归属内容提供方，若内容存在侵权，请进行举报或认领
                        </div>

                        <template slot="bottom-right">
                            {{typeName}} 
                            <span> {{nums}} </span> 次
                            <el-button type="text" v-if="isLogin && nums == 0" @click="dialogVisible=true">去购买</el-button>
                            <el-button type="text" v-if="!isLogin && nums == 0" @click="showLogin">去登录</el-button>&nbsp;
                        </template>
                    </paper-foot>
                </layout-card>

                <!-- <layout-card>
                    <comment
                        objecttype="document"
                        :objectguid="detail.guid"
                    ></comment>
                </layout-card> -->
            </template>

            <template slot="right">
                <!-- <layout-card class="paper-adduser-info">
                    <adduser-info
                    :data="userData"
                    >
                        <div class="total">
                            共上传 {{userData.total}} 篇文件模板
                        </div>
                    </adduser-info>
                </layout-card> -->

                <layout-card class="ceiling" style="width: 350px;">
                    <template slot="head">
                        热门文档
                    </template>

                    <section-hot></section-hot>
                </layout-card>

                <section-relevant class="ceiling" @update="relevantUpdate" style="width: 350px;"></section-relevant>

            </template>

        </layout-detail>

        <!-- <dialog-product :data="detail" v-model="dialogVisible" @close="getUserBuy" @getPaySuccess="setPaySuccess"></dialog-product> -->

        <dialog-product v-model="dialogVisible" :projectids="projectids" @success="setPaySuccess">
        </dialog-product>
    </div>
</template>

<script>
import {buildTdk} from '@config/tdk';

// import DialogProduct from './components/dialog-product.vue';
import DialogProduct from '@/pages/user/center/components/dialog-product.vue';

import CONFIG_PROJECT from '@config/project';
import layoutDetail from '@components/sys/layout-detail';
import layoutCard from '@components/sys/layout-card';
import pageList from './components/detail-page-list';
import btnLoad from './components/btn-load';
import paperFoot from '@components/sys/paper-foot';
import adduserInfo from '@components/sys/adduser-info';

import sectionRelevant from './sections/section-relevant';
import sectionHot from './sections/section-hot';
import Comment from '@components/sys/comment/index';

import appNode from '@js/app-node';
import Ceiling from '@js/Ceiling';

import { mapActions, mapGetters } from 'vuex';
export default {
    head() {
        return buildTdk('document');
    },
    layout: 'client',
    components: {
        DialogProduct,

        layoutDetail,
        layoutCard,
        pageList,
        btnLoad,
        paperFoot,
        adduserInfo,
        sectionRelevant,
        sectionHot,
        Comment,
    },
    async asyncData(context) {
        let [detail] = await Promise.all([
            appNode.ssrReq
                .call(context, `${context.store.state.api.tbUrl}/document/detail.json`, {
                    guid: context.params.guid,
                })
                .then((data) => data),
        ]);

        // detail.taglist = detail.taglist.filter(item => item.classifycode === 'TC1');

        var tableData = detail.previewlist
                .sort(function (a, b) {
                    return Number(a.newtypecode) - Number(b.newtypecode);
                })
                .slice(0, 10),
            docname = detail.docname,
            userData = {
                name: detail.authorname,
                total: detail.authordocamount,
            },
            bread = [
                {
                    route: '/document',
                    title: '文件模板',
                },
                {
                    route: context.route.fullPath,
                    title: docname,
                },
            ];

        return {
            detail,
            tableData,
            docname,
            bread,
            userData,
        };
    },
    data() {
        return {
            ceilingRight: null,
            ceilingBottom: null,
            dialogVisible: false,

            projectids:"9",
            productcode:'TBFAXZ',
            typeName: '投标方案下载',
            nums:0,
            ispermission: false,
            isLogin: true,
        };
    },
    computed: {
        total() {
            if (!this.detail.previewlist) {
                return 0;
            }

            return this.detail.previewlist.length;
        },
        pageRemain() {
            if (!this.total) return 0;

            return this.total - this.tableData.length;
        },
        ...mapGetters({
            nickname: 'userinfo/getNickname',
        })
    },
    methods: {
        ...mapActions({
            showLogin: 'global-dialog/showLogin',
        }),

        loadMoreHandler() {
            const SERIAL_CODE = this.$cookies.get('SERIAL_CODE');
            const that = this;

            var fun = function () {
                var data = that.detail.previewlist.slice(10, that.detail.previewlist.length);

                that.tableData = [...that.tableData, ...data];
            };

            if (!SERIAL_CODE) {
                this.showLogin(() => {
                    fun();
                });
            } else {
                fun();
            }
        },
        // 下载事件
        downloadFile(val) {
            const that = this;
            var fun = function () {
                if( !that.ispermission){
                    that.useNums();
                }

                that.$post(
                    `${that.$store.state.api.tbUrl}/document/download.json`,
                    {
                        fileguid: that.detail.fileguid,
                        guid: that.detail.guid,
                        docname: that.detail.docname,
                        uploader: that.detail.authorname,
                    },
                    (data) => {}
                );
                var search = toSearch({
                    fileguid: that.detail.fileguid,
                });
                showMsg( '下载成功', 'success');
                if(val == 'filelibrary'){
                    downloader(`${that.$store.state.api.fileUrl}/web/document/filedownload.do/${search}`);
                } else{
                    downloader(`${that.$store.state.api.webUrl}/tbfaupload/fileguidcommon.json${search}`);
                }
            };
            fun();
        },

        downloadAll() {
            const SERIAL_CODE = this.$cookies.get('SERIAL_CODE');
            var that = this;

            new Chain()
                .link((next) => {
                    if (!SERIAL_CODE) {
                        this.showLogin(() => {
                            this.downloadAll();
                        });
                        return true;
                    }

                    next();
                })
                // 按照 下载次数判断，有就消耗次数下载，无就去过购买
                .link((next) => {
                    //点击导出
                    //   'userinfo/userDownFile', { typeName, nums ,haveNums ,noNums,  noLogin}
                    this.$store.dispatch('userinfo/userPowerLook', {
                        typeName: '投标方案下载',
                        userData: {
                            productcode: this.productcode,
                            objectname: this.detail.docname,
                            objectguid: this.detail.guid,
                        },
                        havePower: () => {
                            ShowConfirm('本次下载免费，是否下载当前文档', 'warning', () => {
                                that.ispermission = true;
                                that.downloadFile();
                            });
                        },
                        haveNums: () => {
                            this.ispermission = false;
                            this.byNums()
                        },
                        noNums: () => {
                            this.ispermission = false;
                            this.dialogVisible = true;
                        },
                    });
                    
                    next();
                })

                //     //  付费下载接口
                // .link((next) => {
                //     this.$get(
                //         `${this.$store.state.api.sysUrl}/tb/document/docdownauth.json`,
                //         {
                //             docid: this.detail.guid,
                //         },
                //         (data) => {
                //             console.log(data);
                //             if (data.status == '1') {
                //                 this.downloadFile(data.downloadtype);
                //                 return true;
                //             } else {
                //                 //打开弹窗，付费购买
                //                 this.openDiago();
                //             }
                //         }
                //     );
                //     next();
                // })
                .run();
        },
        //花费次数购买
        byNums(){
            ShowConfirm('本次下载需消耗一次次数，是否下载当前文档', 'warning', () => {
                this.downloadFile();
            });
        },
        //使用次数
        useNums() {
            this.$store.dispatch('userinfo/userUsedNums', {
                userData: {
                    productcode: this.productcode,
                    objectguid:this.detail.guid,
                    objectname: this.detail.docname,
                },
                success: data => {
                    this.getNums();
                },
            })
            this.getNums();
        },

        getNums() {
            this.$get(`${this.$store.state.api.tbUrl}/consume/getsurplusnum.json`, {
                    productcode: this.productcode,
                }, data => {
                    this.nums = data.count
                })
        },

        openDiago() {
            this.dialogVisible = true;
        },

        // 支付成功，下载
        setPaySuccess() {
            // status = 1,直接调用下载接口，
            this.downloadAll();
            this.getNums();
        },

        relevantUpdate() {
            this.ceilingRight.destroy();

            var ceilingDom = document.querySelectorAll('.ceiling'),
                lastDom = ceilingDom[ceilingDom.length - 1];

            this.ceilingRight = new Ceiling({
                el: lastDom,
                con: document.querySelector('.page-body'),
            });
        },
        getUserBuy() {},
        
        checkIsLogin(){
            this.$store.dispatch('userinfo/checkIsLoginNoDoing',{
                login:()=>{
                    this.isLogin = false;
                },
                noLogin: () =>{
                    this.isLogin = false;
                },
            })
        },
    },
    created() {},
    mounted() {
        this.ceilingRight = new Ceiling({
            el: document.querySelector('.ceiling'),
        });

        this.getNums();
        this.checkIsLogin();
    },
};
</script>

<style lang="scss" scoped>
@import '@css/var.scss';

.document {
    margin-top: 12px;
    .file {
    }
}

.copyright {
    margin-bottom: 34px;
    color: #666;
}
</style>
 